<template>
  <div class="app-container">
    <div style="text-align: center;margin-bottom: 30px">
      用户{{ createStatus ? '新增' : '更新' }}
    </div>
    <el-row :gutter="10">
      <el-form :model="userForm" ref="userForm" :rules="userFromRules" label-width="100px">
        <el-col :xs="24" :sm="24" :md=5 :lg="5" :xl="5">
          <el-form-item label="头像" prop="avatar">
            <el-upload
                class="avatar-uploader"
                :headers="headers"
                :action="uploadImg"
                :data="{type:'avatar'}"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload">
              <img v-if="userForm.avatar&& imgFlag == false" :src="userForm.avatar" class="avatar">
              <i v-else-if="!userForm.avatar&& imgFlag == false" class="el-icon-plus avatar-uploader-icon"></i>
              <el-progress v-if="imgFlag == true" type="circle" :percentage="imgUploadPercent"
                           style="margin-top:30px;"></el-progress>
            </el-upload>
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="24" :md="24" :lg="18" :xl="18">
          <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="8">
            <el-form-item label="用户名" prop="userName">
              <el-input type="text" v-model="userForm.userName" placeholder="请输入用户名"
                        clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="8">
            <el-form-item label="姓名" prop="name">
              <el-input v-model="userForm.name" placeholder="请输入姓名" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="8">
            <el-form-item label="可登录权限" prop="type">
              <el-select placeholder="请选择可登录权限" v-model="userForm.type" clearable style="width: 100%">
                <el-option label="app" :value=2></el-option>
                <el-option label="pc" :value=1></el-option>
                <el-option label="全部" :value=0></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="8">
            <el-form-item label="联系邮箱" prop="email">
              <el-input type="text" v-model="userForm.email" placeholder="请输入联系邮箱"
                        clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="8">
            <el-form-item label="联系电话" prop="mobile">
              <el-input type="text" v-model="userForm.mobile" placeholder="请输入联系电话"
                        clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="8" >
            <el-form-item label="所属主体" prop="flagId" v-if="enterPriseHidden">
              <el-cascader
                  v-model="userForm.flagId"
                  :options="enterpriseDominantList"
                  :props="{ expandTrigger: 'hover',emitPath:false }"
                  :show-all-levels="false"
                  style="width: 100%"
                  @change="handleChange"></el-cascader>
<!--              <el-select v-model="userForm.flagId" filterable placeholder="请选择主体" @change="enterpriseChange" style="width: 100%">-->
<!--                <el-option v-for="(item,index) in enterpriseDominantList" :key="index" :value="item.ucId"-->
<!--                           :label="item.name"></el-option>-->
<!--              </el-select>-->
            </el-form-item>
          </el-col>
<!--          <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="8">-->
<!--            <el-form-item label="省市县" prop="userLocal">-->
<!--              <city-select :local="userForm.userLocal" v-on:handleChange="getCity"></city-select>-->
<!--            </el-form-item>-->
<!--          </el-col>-->
          <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="8">
            <el-form-item label="详细地址" prop="address">
              <el-input type="text" v-model="userForm.address" placeholder="请输入详细地址"
                        clearable></el-input>
            </el-form-item>
          </el-col>
          <!--                            <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="8">-->
          <!--                                <el-form-item label="证件类型" prop="documentType">-->
          <!--                                    <el-select v-model="userForm.documentType" placeholder="请选择企业类型"-->
          <!--                                               style="width: 100%">-->
          <!--                                        <el-option :value="0" label="居民身份证"></el-option>-->
          <!--                                    </el-select>-->
          <!--                                </el-form-item>-->
          <!--                            </el-col>-->
          <!--                            <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="8">-->
          <!--                                <el-form-item label="证件号" prop="documentNumber">-->
          <!--                                    <el-input type="text" v-model="userForm.documentNumber" placeholder="请输入证件号 "-->
          <!--                                              clearable></el-input>-->
          <!--                                </el-form-item>-->
          <!--                            </el-col>-->
          <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="8">
            <el-form-item label="用户状态" prop="status">
              <el-switch
                  v-model="userForm.status"
                  active-color="#13ce66"
                  inactive-color="#ff4949">
              </el-switch>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="8">
            <el-form-item label="性别" prop="sex">
              <el-radio-group v-model="userForm.sex">
                <el-radio :label="1">男</el-radio>
                <el-radio :label="2">女</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>

          <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="8">
            <el-form-item label="所属角色" prop="roleId">
              <el-select v-model="userForm.roleId" filterable placeholder="请选择角色" style="width: 100%">
                <el-option v-for="(item,index) in roleList" :key="index" :value="item.ucId"
                           :label="item.name"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="8">
            <el-form-item v-if="createStatus" label="密码" prop="password">
              <el-input type="password" v-model="userForm.password" placeholder="请输入密码" clearable></el-input>
            </el-form-item>
            <el-form-item v-else label="重置密码" prop="password">
              <el-switch
                  style="width: 50%"
                  v-model="userForm.resetPassword"
                  active-color="#13ce66"
                  inactive-color="#ff4949"
                  active-text="重置"
                  inactive-text="不重置"
                  @change="resetPassword">
              </el-switch>
              <el-input v-if="userForm.resetPassword" style="width: 50%" type="password" v-model="userForm.password"
                        placeholder="请输入新密码" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="8">
            <el-form-item label="是否指战员" prop="isCommander" v-if="enterPriseHidden1">
              <el-switch
                  v-model="userForm.isCommander"
                  active-color="#13ce66"
                  inactive-color="#ff4949">
              </el-switch>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="8" v-show="postShow">
            <el-form-item label="所属岗位" prop="postCode">
              <el-select v-model="postCodeList" multiple placeholder="请选择岗位">
                <el-option v-for="(item,index) in postList" :key="index" :value="item.postCode"
                           :label="item.postName"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-col>
      </el-form>
    </el-row>


    <div slot="footer" style="text-align: center" class="dialog-footer">
      <el-button @click="cancelEnterprise">取 消</el-button>
      <el-button :loading="addLoading" v-if="createStatus" type="primary" @click="createEnterprise">创 建
      </el-button>
      <el-button :loading="addLoading" v-else type="primary" @click="updateEnterprise">修 改</el-button>
    </div>
  </div>
</template>

<script>
import {addInUser, getInUserVo, updateInUser, getInEnterpriseVo, getInEnterpriseList} from "@/api/enterprise";
import CitySelect from "@/components/citySelect/index.vue";
import {uploadImg} from "@/api/common";
import {getToken} from "@/utils/auth";
import {getInEnterpriseDominantList,getEnterpriseGroup} from "@/api/enterpriseDominant";
import {getInEnterpriseDominantVo} from "@/api/enterprise";
import {getInRoleList} from "@/api/role";
import {getPostList} from "@/api/post";
import {isExit} from "@/api/validator";

export default {
  name: "userEdit",
  components: {},
  data() {
    let checkData = (rule, value, callback) => {
      if (value == '') {
        callback(new Error('请输入用户名'))
      } else if (/[\u4E00-\u9FA5]/g.test(value)) {
        callback(new Error('用户名不能输入汉字!'))
      } else {
        callback()
      }
    }
    let checkPhone = (rule, value, callback) => {
      const reg = /^0?(13[0-9]|15[012356789]|18[0-9]|14[578]|16[6]|17[035768]|19[19])[0-9]{8}$/
      if (reg.test(value)) {
        return callback();
      }
      callback('请输入合法的手机号');
    };
    return {
      uploadImg,
      userName: "",
      mobile: "",
      postShow: false,
      userForm: {
        qrCode: "null",
        type: 1,
        status: true,
        sex: 1,
        isCommander: false
      },
      userFromRules: {
        address: [{required: true, message: '详细地址不能为空', trigger: 'blur'}],
        userName: [
            {required: true, trigger: 'blur', message: '用户名不能为空'},
          {
            validator: (rule, value, callback) => {
              if (!value) {
                callback(new Error('用户名不能为空'))
              } else {
                let id = 0
                if(this.userName && value == this.userName)
                  id = 1
                isExit({userName:value, id: id}).then(res=>{
                  if (res.data) {
                    callback(new Error('该用户名已经存在'))
                  } else {
                    callback()
                  }
                })
              }
            },
            trigger:['change','blur'],
          }
        ],
        mobile: [
          {validator: checkPhone, required: true, trigger: 'blur'},
          {
            validator: (rule, value, callback) => {
              if (!value) {
                callback(new Error('手机号不能为空'))
              } else {
                let id = 0
                if(this.mobile && value == this.mobile)
                  id = 1
                isExit({mobile:value, id: id}).then(res=>{
                  if (res.data) {
                    callback(new Error('该手机号已经存在'))
                  } else {
                    callback()
                  }
                })
              }
            },
            trigger:['change','blur'],
          }
        ],
        userLocal: [{required: true, message: '省市县不能为空', trigger: 'blur'}],
        password: [{required: true, message: '密码   不能为空', trigger: 'blur'}],
        flagId: [{required: true, message: '所属主题不能空', trigger: 'change'}],
        type: [{required: true, message: '请选择可登录权限', trigger: 'change'}],
      },
      addLoading: false,
      enterpriseList: [],
      enterpriseDominantList: [],
      roleList: [],
      imgFlag: false,
      imgUploadPercent: 0,
      //选中岗位编码数组
      postCodeList:[],
      //岗位列表
      postList:[]
    }
  },
  computed: {
    createStatus() {
      return this.$route.params.ucId == '0'
    },
    headers() {
      return {
        'Authorization': getToken()
      }
    },
    enterPriseHidden() {
      let roleCode = this.$store.getters.roleCode;
      return roleCode == "XT-ADMIN" || roleCode == "ZD-ADMIN" || roleCode == "DD-ADMIN" || roleCode == "JW-ADMIN"
    },
    enterPriseHidden1() {
      let roleCode = this.$store.getters.roleCode;
      return roleCode == "XT-ADMIN" || roleCode == "ZZ-ADMIN"
    }
  },
  created() {
    // let userInfo = this.$store.getters.userInfo;
    // this.getInEnterpriseDominantVo(userInfo.flagId)
    this.getInRoleList()
    this.getEnterpriseGroup()
    this.getPostList()
    if (!this.createStatus) {
      let ucId = this.$route.params.ucId
      this.getInUserVo(ucId)
    }
  },
  methods: {
    handleChange(value){
      console.log(value)
    },
    getInEnterpriseDominantVo(ucid) {
      getInEnterpriseDominantVo({ucId: ucid}).then(res => {
        // console.log(res)
        this.userForm.userLocal = [res.data.province, res.data.city, res.data.county]
        this.userForm.province = res.data.province
        this.userForm.city = res.data.city
        this.userForm.county = res.data.county
        this.userForm.address = res.data.address
        if(res.data.dominantType == 6 || res.data.dominantType == 7){
          this.postShow = true
        }else{
          this.postShow = false
        }
      }).catch(res => {
        console.log("失败")
      })
    },
    enterpriseChange(item){
      this.getInEnterpriseDominantVo(item)
    },
    getPostList(){
      getPostList({}).then(res=>{
        this.postList = res.data
      })
    },
    getInRoleList() {
      getInRoleList({}).then(res => {
        this.roleList = res.data
      }).catch(error => {

      })
    },
    getInUserVo(val) {
      getInUserVo({ucId: val}).then(res => {
        this.userForm = res.data
        this.userName = this.userForm.userName
        this.mobile = this.userForm.mobile
        this.userForm.userLocal = [this.userForm.province, this.userForm.city, this.userForm.county]
        this.postCodeList = this.userForm.postCode.split(",")
      }).catch(res => {

      })
    },
    cancelEnterprise() {
      window.history.back()
    },
    createEnterprise() {
      this.addLoading = true
      this.userForm.postCode=this.postCodeList.join(",");
      this.$refs['userForm'].validate(valid => {
        if (valid) {
          addInUser(this.userForm).then(res => {
            this.addLoading = false
            this.$notify.success({
              title: '成功',
              message: "添加用户成功"
            })
            this.cancelEnterprise()
          }).catch(res => {
            this.addLoading = false
            this.$notify.error({
              title: '失败',
              message: res.msg
            })
          })
        } else {
          this.addLoading = false
          console.log("表单验证不通过")
        }
      })
    },
    updateEnterprise() {
      this.addLoading = true
      this.userForm.postCode=this.postCodeList.join(",");
      this.$refs['userForm'].validate(valid => {
        if (valid) {
          updateInUser(this.userForm).then(res => {
            this.addLoading = false
            this.$notify.success({
              title: '成功',
              message: "更新用户成功"
            })
            this.cancelEnterprise()
          }).catch(res => {
            this.addLoading = false
            this.$notify.error({
              title: '失败',
              message: res.msg
            })
          })
        } else {
          this.addLoading = false
          console.log("表单验证不通过")
        }
      })
    },
    //重置密码操作
    resetPassword(val) {
      if (val) {
        this.userForm.password = null
      }
    },
    handleAvatarSuccess(res, file) {
      //图片上传成功
      console.log(res)
      this.imgFlag = false;
      this.userForm.avatar = res.data;
    },
    uploadImgProcess(event, file, fileList) {
      this.imgFlag = true;
      this.imgUploadPercent = file.percentage.toFixed(0);
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg';
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    },
    //选择位置信息
    getCity(val) {
      this.userForm.userLocal = val
      this.userForm.province = val[0]
      this.userForm.city = val[1]
      this.userForm.county = val[2]
    },
    getEnterpriseGroup() {
      getEnterpriseGroup({}).then(res => {
        this.enterpriseDominantList = res.data
      })
    },
  }
}
</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 149px;
  height: 149px;
  line-height: 149px;
  text-align: center;
}

.avatar {
  width: 149px;
  height: 149px;
  display: block;
}
</style>
